from contextlib import asynccontextmanager

from fastapi import FastAPI
from tortoise import Tortoise

from app.core.exceptions import SettingNotFound
from app.core.init_app import (
    init_data,
    make_middlewares,
    register_exceptions,
    register_routers,
)
from app.core.init_middlewares import get_redis_connection, init_kafka
from aiokafka import AIOKafkaConsumer
import asyncio
from app.log.log import logger

try:
    from app.settings.config import settings
except ImportError:
    raise SettingNotFound("Can not import settings")

async def consume_message(consumer: AIOKafkaConsumer):
    async for msg in consumer:
        logger.info(f"topic: {msg.topic}, partition: {msg.partition}, offset: {msg.offset}, key: {msg.key}, value: {msg.value}, timestamp: {msg.timestamp}")

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_data()
    redis = await get_redis_connection()
    producer, consumer = await init_kafka()
    asyncio.create_task(consume_message(consumer))
    
    app.state.kafka_producer = producer
    app.state.kafka_consumer = consumer
    
    yield
    
    await Tortoise.close_connections()
    await redis.close()
    await producer.stop()
    await consumer.stop()

def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.APP_TITLE,
        description=settings.APP_DESCRIPTION,
        version=settings.VERSION,
        openapi_url="/openapi.json",
        middleware=make_middlewares(),
        lifespan=lifespan,
    )
    register_exceptions(app)
    register_routers(app, prefix="/api")
    return app


app = create_app()